package com.xuerhua.yxt.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xuerhua.yxt.common.AppUser;
import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.CoachStatus;
import com.xuerhua.yxt.common.enums.CoachType;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.model.Grid;
import com.xuerhua.yxt.model.StudentCoach;
import com.xuerhua.yxt.model.StudentInfo;
import com.xuerhua.yxt.model.StudentLeave;
import com.xuerhua.yxt.page.OrderBy;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.CoachQueryVO;
import com.xuerhua.yxt.service.IStudentCoachService;
import com.xuerhua.yxt.service.IStudentLeaveService;
import com.xuerhua.yxt.service.IStudentService;
import com.xuerhua.yxt.service.ITeacherService;
import com.xuerhua.yxt.utils.BeanUtils;
import com.xuerhua.yxt.utils.DateUtil;
import com.xuerhua.yxt.utils.StringUtil;
import com.xuerhua.yxt.view.StudentCoachView;
import com.xuerhua.yxt.vo.CourseCoachReqVO;
import com.xuerhua.yxt.wechat.utils.TemplateUtil;

@Controller
public class CourseCoachController extends BaseController {
	
	private Logger logger = LoggerFactory.getLogger(CourseCoachController.class);
	
	@Autowired
	private IStudentCoachService studentCoachService;
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private IStudentLeaveService studentLeaveService;
	@Autowired
	private IStudentService studentService;

	@RequestMapping(Const.STUDENT_ROLE + MenuConst.COURSE_COACH)
	public String studentCourseCoach() {
		return "course/studentCoach";
	}
	
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.COURSE_COACH)
	public String teacherCourseCoach() {
		AppUser appUser = getAppUser();
		int count = teacherService.selectCountByOpenid(appUser.getOpenid());
		if(count > 0) {
			//班主任页面
			return "course/teacherMainCoach";
		}
		return "course/teacherCoach";
	}
	
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.COURSE_COACH + "/add")
	public String teacherAddCourseCoach(Model model) {
		String leaveId = request.getParameter("leaveId");
		if(StringUtils.isNotBlank(leaveId)) {
			CoachQueryVO queryVO = new CoachQueryVO();
			queryVO.setTeacherId(getAppUser().getTeacher().getId());
			queryVO.setLeaveId(Integer.valueOf(leaveId));
			queryVO.setSchoolId(getAppUser().getTeacher().getSchoolId());
			List<StudentCoachView> list = studentCoachService.selectCoachByParam(queryVO);
			model.addAttribute("coach", list.get(0));
		}
		return "course/teacherAddCoach";
	}
	
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.COURSE_COACH + "/addUpdate")
	@ResponseBody Object teacherCreateCourseCoach(CourseCoachReqVO vo) {
		try {
			StudentCoach coach = BeanUtils.copyAs(vo, StudentCoach.class);
			coach.setCoachTime(DateUtil.strToDate(vo.getCoachDate(), DateUtil.DEFAULT_DATE_FORMAT1));
			if(vo.getCoachType().equals(CoachType.COACH_LEAVE.getCode())) {	//学生请假
				coach.setCoachStatus(CoachStatus.COACHED.getCode());
				coach.setUpdateTime(new Date());
				studentCoachService.updateByPrimaryKeySelective(coach);
			}else {
				AppUser appUser = getAppUser();
				coach.setSchoolId(appUser.getTeacher().getSchoolId());
				coach.setSchoolName(appUser.getTeacher().getSchoolName());
				coach.setTeacherId(appUser.getTeacher().getId());
				coach.setTeacherName(appUser.getTeacher().getName());
				coach.setTermId(getCurrentTerm().getId());
				List<StudentInfo> studentList = studentService.selectListByIds(vo.getStudentIds());
				if(!StringUtil.isNullOrEmpty(studentList)) {
					for(StudentInfo studentInfo : studentList) {
						coach.setStudentId(studentInfo.getId());
						coach.setStudentName(studentInfo.getName());
						studentCoachService.insertSelective(coach);
					}
				}
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----teacherCreateCourseCoach error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.COURSE_COACH + "/noCoach")
	@ResponseBody Object teacherNoCoach(CourseCoachReqVO vo) {
		try {
			StudentCoach coach = BeanUtils.copyAs(vo, StudentCoach.class);
			coach.setUpdateTime(new Date());
			studentCoachService.updateByPrimaryKeySelective(coach);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----teacherNoCoach error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(Const.TEACHER_ROLE + MenuConst.COURSE_COACH + "/remindCoach")
	@ResponseBody Object teacherRemindCoach(Integer leaveId) {
		try {
			CoachQueryVO queryVO = new CoachQueryVO();
			queryVO.setLeaveId(leaveId);
			queryVO.setCoachStatus(CoachStatus.COACHING.getCode());
			queryVO.setSchoolId(getAppUser().getTeacher().getSchoolId());
			List<StudentCoachView> list = studentCoachService.selectCoachByParam(queryVO);
			String reqUrl = Const.BASEPATH + "/ls/course/coach";
			StudentLeave studentLeave = studentLeaveService.selectByPrimaryKey(leaveId);
			for (StudentCoachView view : list) {
				String gradeClass = view.getGradeText() + "（" + view.getClazz() + "）班";
				TemplateUtil.studentCoachSend(view.getTeacherOpenid(), view.getTeacherName(), view.getStudentName(), 
						gradeClass, studentLeave.getStartTime(), studentLeave.getEndTime(), studentLeave.getLeaveReason(), reqUrl);
			}
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("----teacherNoCoach error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping(Const.TEACHER_ROLE +  MenuConst.COURSE_COACH + "/pending")
	@ResponseBody Object pendingCoachQuery() {
		AppUser appUser = getAppUser();
		StudentCoach sc = new StudentCoach();
		sc.setTeacherId(appUser.getTeacher().getId());
		sc.setSchoolId(appUser.getTeacher().getSchoolId());
		return studentCoachService.selectPendingCoachListForTeacher(sc);
	}
	
	@RequestMapping(Const.TEACHER_ROLE +  MenuConst.COURSE_COACH + "/page/query")
	@ResponseBody Object coachPageQuery(CoachQueryVO vo) {
		try {
			Page<StudentCoachView> page = new Page<StudentCoachView>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("coachTime", "desc"));
			sorts.add(new OrderBy("createTime", "desc"));
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setTeacherId(appUser.getTeacher().getId());
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<StudentCoachView> list = studentCoachService.selectCoachListByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("----coachPageQuery error={}", e);
		}
		return null;
	}
	
	@RequestMapping(Const.TEACHER_ROLE +  MenuConst.COURSE_COACH + "/class/page/query")
	@ResponseBody Object classCoachPageQuery(CoachQueryVO vo) {
		try {
			Page<StudentCoachView> page = new Page<StudentCoachView>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("leaveEndTime", "desc"));
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getTeacher().getSchoolId());
			vo.setTeacherId(appUser.getTeacher().getId());
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<StudentCoachView> list = studentCoachService.selectCoachListForClassByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("----classCoachPageQuery error={}", e);
		}
		return null;
	}
	
	@RequestMapping(Const.STUDENT_ROLE +  MenuConst.COURSE_COACH + "/page/query")
	@ResponseBody Object studentCoachPageQuery(CoachQueryVO vo) {
		try {
			Page<StudentCoachView> page = new Page<StudentCoachView>();
			Grid grid = new Grid();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("leaveEndTime", "desc"));
			AppUser appUser = getAppUser();
			vo.setSchoolId(appUser.getParent().getSchoolId());
			vo.setStudentId(appUser.getParent().getStudentId());
			page.setSorts(sorts);
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(vo.getRows());
			List<StudentCoachView> list = studentCoachService.selectCoachListForStudentByPage(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return grid;
		} catch (Exception e) {
			logger.error("----studentCoachPageQuery error={}", e);
		}
		return null;
	}
	
}
